// src/lib/axios.ts
import axios, {
  type AxiosInstance,
  type AxiosRequestConfig,
  type AxiosResponse,
} from "axios";
import { message } from "antd";
import { BASE_URL } from "./env";

// 定义统一响应数据结构
interface ResponseData<T = any> {
  error: string;
  code: number;
  data: T;
  message?: string;
}

// 扩展 axios 请求配置类型
declare module "axios" {
  interface AxiosRequestConfig {
    // 是否显示全局错误提示（默认true）
    showError?: boolean;
    // 自定义错误提示内容
    errorMessage?: string;
  }
}

const createAxiosInstance = (): AxiosInstance => {
  const instance = axios.create({
    baseURL: BASE_URL,
    timeout: 10000,
    headers: {
      "Content-Type": "multipart/form-data",
    },
  });

  // 请求拦截器
  instance.interceptors.request.use((config: AxiosRequestConfig | any) => {
    // 安全获取 localStorage（SSR 兼容）
    const token =
      typeof window !== "undefined" ? localStorage.getItem("token") : null;

    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  });

  // 响应拦截器
  instance.interceptors.response.use(
    (response: AxiosResponse<ResponseData>) => {
      // 处理二进制数据响应（如文件下载）
      if (response.config.responseType === "blob") {
        return response;
      }
      const { data } = response;
      console.log(response, "response");
      // 自定义业务状态码处理
      if (response.data?.code !== 200) {
        console.log(222);
        message.error(
          `${data || ""}-${data?.error || ""}-${data?.data?.msg}-【code:${
            data?.code
          }】`
        );
        // alert(data?.msg);
        return Promise.reject(response.data);
      }
      return response.data.data;
    },
    (error) => {
      console.log(error, "error");
      const config = error.config || {};
      let errorMessage = config.errorMessage || "";
      console.log(error.response, "error.response");
      // HTTP 状态码处理
      if (error.response) {
        switch (error.response.status) {
          case 401:
            errorMessage = "登录已过期，请重新登录";
            window.location.href = "/login"; // 跳转登录页
            break;
          case 403:
            errorMessage = "您没有权限访问该资源";
            break;
          case 404:
            errorMessage = "请求资源不存在";
            break;
          case 500:
            errorMessage = "服务器内部错误";
            break;
          default:
            errorMessage = error.response.data?.message || "未知错误";
        }
      } else if (error.code === "ECONNABORTED") {
        errorMessage = "请求超时，请检查网络连接";
      } else if (error.message === "Network Error") {
        errorMessage = "网络异常，请检查网络连接";
      }

      // 显示 Antd 错误提示
      if (config.showError !== false && errorMessage) {
        message.error({
          content: errorMessage,
          duration: 2,
        });
      }

      return Promise.reject(error);
    }
  );

  return instance;
};

const api = createAxiosInstance();

export default api;
